

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文转载自《https:&#x2F;&#x2F;www.cnblogs.com&#x2F;digdeep&#x2F;p&#x2F;4859575.html》 OpenResty 介绍OpenResty 官网：http:&#x2F;&#x2F;openresty.org&#x2F; OpenResty 是一个nginx和它的各种三方模块的一个打包而成的软件平台。最重要的一点是它将lua&#x2F;luajit打包了进来，使得我们可以使用lua脚本来进行web的开发。有了lua，我们可以借">
<meta property="og:type" content="article">
<meta property="og:title" content="OpenResty(nginx+lua)基础 (转载)">
<meta property="og:url" content="http://fly542.cn/2022/04/06/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/07%E5%BA%94%E7%94%A8%E8%BD%AF%E4%BB%B6/00OpenResty(nginx+lua)%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="本文转载自《https:&#x2F;&#x2F;www.cnblogs.com&#x2F;digdeep&#x2F;p&#x2F;4859575.html》 OpenResty 介绍OpenResty 官网：http:&#x2F;&#x2F;openresty.org&#x2F; OpenResty 是一个nginx和它的各种三方模块的一个打包而成的软件平台。最重要的一点是它将lua&#x2F;luajit打包了进来，使得我们可以使用lua脚本来进行web的开发。有了lua，我们可以借">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fly542.cn/2022/04/06/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/07%E5%BA%94%E7%94%A8%E8%BD%AF%E4%BB%B6/00OpenResty(nginx+lua)%E5%9F%BA%E7%A1%80/1.png">
<meta property="article:published_time" content="2022-04-06T03:15:11.000Z">
<meta property="article:modified_time" content="2024-06-06T07:08:58.988Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="nginx">
<meta property="article:tag" content="lua">
<meta property="article:tag" content="openresty">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://fly542.cn/2022/04/06/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/07%E5%BA%94%E7%94%A8%E8%BD%AF%E4%BB%B6/00OpenResty(nginx+lua)%E5%9F%BA%E7%A1%80/1.png">
  
  
  <title>OpenResty(nginx+lua)基础 (转载) - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="OpenResty(nginx+lua)基础 (转载)">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-04-06 11:15" pubdate>
        2022年4月6日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      17k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      142 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">OpenResty(nginx+lua)基础 (转载)</h1>
            
            <div class="markdown-body">
              <p>本文转载自《<a target="_blank" rel="noopener" href="https://www.cnblogs.com/digdeep/p/4859575.html%E3%80%8B">https://www.cnblogs.com/digdeep/p/4859575.html》</a></p>
<h1 id="OpenResty-介绍"><a href="#OpenResty-介绍" class="headerlink" title="OpenResty 介绍"></a>OpenResty 介绍</h1><p>OpenResty 官网：<a target="_blank" rel="noopener" href="http://openresty.org/">http://openresty.org/</a></p>
<p>OpenResty 是一个nginx和它的各种三方模块的一个打包而成的软件平台。最重要的一点是它将lua/luajit打包了进来，使得我们可以使用lua脚本来进行web的开发。有了lua，我们可以借助于nginx的异步非阻塞的功能，达到使用 lua 异步并发访问后端的 MySQL, PostgreSQL, Memcached, Redis等等服务。特别是特有的 ngx.location.capture_multi 功能让人印象深刻，其可以达到极大的减少浏览器的http连接数量，并且可以异步并发的访问后台 Java/PHP/Python 等等接口。OpenResty 架构的web可以轻松超越Node.js的性能，并且对后端语言没有限制，你可以使用Java/PHP/Python等等各种语言。OpenResty(nginx+lua)可以替代node.js的前端渲染的功能。</p>
<h1 id="安装OpenResty"><a href="#安装OpenResty" class="headerlink" title="安装OpenResty"></a>安装OpenResty</h1><p>先安装依赖：yum install readline-devel pcre-devel openssl-devel gcc</p>
<p>解压： tar zxvf ngx_openresty-1.9.3.1.tar.gz</p>
<p>建立一个软连接：ln -s ngx_openresty-1.9.3.1 openresty</p>
<p>进入目录：cd openresty</p>
<h2 id="编译"><a href="#编译" class="headerlink" title="编译"></a>编译</h2><figure class="highlight livecodeserver"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></div></td><td class="code"><pre><code class="hljs livecodeserver">./configure \<br>             <span class="hljs-comment">--with-cc-opt=&quot;-I/usr/local/include&quot; \</span><br>             <span class="hljs-comment">--with-ld-opt=&quot;-L/usr/local/lib&quot; \</span><br>             <span class="hljs-comment">--prefix=/opt/openresty </span><br><br>... ...<br>Configuration summary<br>  + <span class="hljs-keyword">using</span> <span class="hljs-keyword">system</span> PCRE library<br>  + <span class="hljs-keyword">using</span> <span class="hljs-keyword">system</span> OpenSSL library<br>  + md5: <span class="hljs-keyword">using</span> OpenSSL library<br>  + sha1: <span class="hljs-keyword">using</span> OpenSSL library<br>  + <span class="hljs-keyword">using</span> <span class="hljs-keyword">system</span> zlib library<br><br>  nginx path prefix: <span class="hljs-string">&quot;/opt/openresty/nginx&quot;</span><br>  nginx binary <span class="hljs-built_in">file</span>: <span class="hljs-string">&quot;/opt/openresty/nginx/sbin/nginx&quot;</span><br>  nginx configuration prefix: <span class="hljs-string">&quot;/opt/openresty/nginx/conf&quot;</span><br>  nginx configuration <span class="hljs-built_in">file</span>: <span class="hljs-string">&quot;/opt/openresty/nginx/conf/nginx.conf&quot;</span><br>  nginx pid <span class="hljs-built_in">file</span>: <span class="hljs-string">&quot;/opt/openresty/nginx/logs/nginx.pid&quot;</span><br>  nginx error <span class="hljs-built_in">log</span> <span class="hljs-built_in">file</span>: <span class="hljs-string">&quot;/opt/openresty/nginx/logs/error.log&quot;</span><br>  nginx <span class="hljs-keyword">http</span> access <span class="hljs-built_in">log</span> <span class="hljs-built_in">file</span>: <span class="hljs-string">&quot;/opt/openresty/nginx/logs/access.log&quot;</span><br>  nginx <span class="hljs-keyword">http</span> client request body temporary <span class="hljs-built_in">files</span>: <span class="hljs-string">&quot;client_body_temp&quot;</span><br>  nginx <span class="hljs-keyword">http</span> proxy temporary <span class="hljs-built_in">files</span>: <span class="hljs-string">&quot;proxy_temp&quot;</span><br>  nginx <span class="hljs-keyword">http</span> fastcgi temporary <span class="hljs-built_in">files</span>: <span class="hljs-string">&quot;fastcgi_temp&quot;</span><br>  nginx <span class="hljs-keyword">http</span> uwsgi temporary <span class="hljs-built_in">files</span>: <span class="hljs-string">&quot;uwsgi_temp&quot;</span><br>  nginx <span class="hljs-keyword">http</span> scgi temporary <span class="hljs-built_in">files</span>: <span class="hljs-string">&quot;scgi_temp&quot;</span><br></code></pre></td></tr></table></figure>
<p>其中 –prefix=/opt/openresty 指定了安装目录，不指定的话默认会安装到 /usr/local/openresty 目录下。</p>
<h2 id="编译安装：-make-amp-amp-make-install"><a href="#编译安装：-make-amp-amp-make-install" class="headerlink" title="编译安装： make &amp;&amp; make install"></a>编译安装： make &amp;&amp; make install</h2><figure class="highlight autoit"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs autoit">[root<span class="hljs-symbol">@localhost</span> src]<span class="hljs-meta"># cd /opt/openresty/</span><br>[root<span class="hljs-symbol">@localhost</span> openresty]<span class="hljs-meta"># ls</span><br>bin  luajit  lualib  nginx<br></code></pre></td></tr></table></figure>
<p>可以看到 /opt/openresty 目录下四个文件夹，其中包括了 luajit，nginx。</p>
<p>启动openresty: /opt/openresty/nginx/sbin/nginx -c /opt/openresty/nginx/conf/nginx.conf -p /opt/openresty/nginx/</p>
<figure class="highlight tap"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs tap">[root@localhost src]<span class="hljs-comment"># ps -elf|grep nginx</span><br>1 S root     <span class="hljs-number"> 2076 </span>   <span class="hljs-number"> 1 </span><span class="hljs-number"> 0 </span><span class="hljs-number"> 80 </span> <span class="hljs-number"> 0 </span>-<span class="hljs-number"> 34999 </span>-      21:24 ?        00:00:00 nginx: master process /opt/openresty/nginx/sbin/nginx -c /opt/openresty/nginx/conf/nginx.conf -p /opt/openresty/nginx/<br>5 S nobody   <span class="hljs-number"> 2077 </span><span class="hljs-number"> 2076 </span><span class="hljs-number"> 0 </span><span class="hljs-number"> 80 </span> <span class="hljs-number"> 0 </span>-<span class="hljs-number"> 35045 </span>-      21:24 ?        00:00:00 nginx: worker process                                    <br>0 S root     <span class="hljs-number"> 2079 </span><span class="hljs-number"> 1678 </span><span class="hljs-number"> 0 </span><span class="hljs-number"> 80 </span> <span class="hljs-number"> 0 </span>- <span class="hljs-number"> 1088 </span>-      21:24 pts/1    00:00:00 grep nginx<br></code></pre></td></tr></table></figure>
<p>验证可以访问： curl 127.0.0.1</p>
<h1 id="content-by-lua-和-content-by-lua-file"><a href="#content-by-lua-和-content-by-lua-file" class="headerlink" title="content_by_lua 和 content_by_lua_file"></a>content_by_lua 和 content_by_lua_file</h1><p>nginx 如何嵌入 lua 脚本。方法就是在nginx的配置文件nginx.conf 中使用 content_by_lua 或者 cotent_by_lua_file 指令：</p>
<h2 id="content-by-lua-一般在很简单的lua脚本时使用："><a href="#content-by-lua-一般在很简单的lua脚本时使用：" class="headerlink" title="content_by_lua 一般在很简单的lua脚本时使用："></a>content_by_lua 一般在很简单的lua脚本时使用：</h2><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs stata">location /lua &#123;<br>        <span class="hljs-keyword">set</span> <span class="hljs-variable">$test</span> <span class="hljs-string">&quot;hello, world.&quot;</span>;<br>        content_by_lua &#x27;<br>                ngx.header.content_type = <span class="hljs-string">&quot;text/plain&quot;</span>;<br>                ngx.say(ngx.<span class="hljs-keyword">var</span>.<span class="hljs-keyword">test</span>);<br>        &#x27;;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>访问 <a target="_blank" rel="noopener" href="http://localhost/lua">http://localhost/lua</a> 可以看到输出到页面的  hello, world.</p>
<h2 id="cotent-by-lua-file-适应于复杂的-lua-脚本，专门放入一个文件中："><a href="#cotent-by-lua-file-适应于复杂的-lua-脚本，专门放入一个文件中：" class="headerlink" title="cotent_by_lua_file 适应于复杂的 lua 脚本，专门放入一个文件中："></a>cotent_by_lua_file 适应于复杂的 lua 脚本，专门放入一个文件中：</h2><figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs crmsh"><span class="hljs-keyword">location</span> <span class="hljs-title">/lua2</span> &#123;<br>    <span class="hljs-comment">#lua_code_cache off;</span><br>    content_by_lua_file lua/hello.lua;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>路径相对于 /opt/openresty/nginx</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs awk">[root@localhost lua]<span class="hljs-comment"># pwd</span><br><span class="hljs-regexp">/opt/</span>openresty<span class="hljs-regexp">/nginx/</span>lua<br>[root@localhost lua]<span class="hljs-comment"># cat hello.lua</span><br>ngx.say(<span class="hljs-string">&#x27;hello ngx_lua!!!!&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>本例子中 hello.lua 只包含一句： ngx.say(‘hello ngx_lua!!!!’);</p>
<p>访问 /lua2 :</p>
<figure class="highlight erlang-repl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs erlang-repl">[root@localhost lua]# curl localhost/lua<br>hello ngx_lua!!!!<br></code></pre></td></tr></table></figure>
<p>可以看到访问成功。</p>
<p>在 nginx.conf 文件的 server {.. …} 中加入 lua_code_cache off; 可以方便调试lua脚本，修改lua脚本之后，不需要 reload nginx.</p>
<p>openresty 中的 nginx 嵌入 luajit 的原理：</p>
<img src="/2022/04/06/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/07%E5%BA%94%E7%94%A8%E8%BD%AF%E4%BB%B6/00OpenResty(nginx+lua)%E5%9F%BA%E7%A1%80/1.png" srcset="/img/loading.gif" lazyload class="" title="ngx_lua工作原理">
<p>每一个nginx的进程中都嵌入了一个 luajit的虚拟机，来执行lua脚本。nginx将lua脚本的执行交给了luajit vm.</p>
<h1 id="ngx-lua-的指令-和-API"><a href="#ngx-lua-的指令-和-API" class="headerlink" title="ngx_lua 的指令 和 API"></a>ngx_lua 的指令 和 API</h1><h2 id="ngx访问lua指令"><a href="#ngx访问lua指令" class="headerlink" title="ngx访问lua指令"></a>ngx访问lua指令</h2><p>上面我们说到 nginx 嵌入 lua 脚本可以使用 content_by_lua 和 content_by_lua_file，它们其实是<code>指令(Directives)</code>，类似的<code>指令</code>还有很多，</p>
<p>具体参见：<a target="_blank" rel="noopener" href="https://www.nginx.com/resources/wiki/modules/lua/#directives">https://www.nginx.com/resources/wiki/modules/lua/#directives</a></p>
<figure class="highlight autohotkey"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs autohotkey">lu<span class="hljs-built_in">a_use</span>_default_type<br>lu<span class="hljs-built_in">a_code</span>_cache<br>lu<span class="hljs-built_in">a_regex</span>_cache_max_entries<br>lu<span class="hljs-built_in">a_regex</span>_match_limit<br>lu<span class="hljs-built_in">a_package</span>_path<br>lu<span class="hljs-built_in">a_package</span>_cpath<br>init_by_lua<br>init_by_lu<span class="hljs-built_in">a_file</span><br>init_worker_by_lua<br>init_worker_by_lu<span class="hljs-built_in">a_file</span><br>set_by_lua<br>set_by_lu<span class="hljs-built_in">a_file</span><br>content_by_lua<br>content_by_lu<span class="hljs-built_in">a_file</span><br>rewrite_by_lua<br>rewrite_by_lu<span class="hljs-built_in">a_file</span><br>access_by_lua<br>access_by_lu<span class="hljs-built_in">a_file</span><br>header_filter_by_lua<br>header_filter_by_lu<span class="hljs-built_in">a_file</span><br>body_filter_by_lua<br>body_filter_by_lu<span class="hljs-built_in">a_file</span><br>log_by_lua<br>log_by_lu<span class="hljs-built_in">a_file</span><br>lu<span class="hljs-built_in">a_need</span>_request_body<br>lu<span class="hljs-built_in">a_shared</span>_dict<br>lu<span class="hljs-built_in">a_socket</span>_connect_timeout<br>lu<span class="hljs-built_in">a_socket</span>_send_timeout<br>lu<span class="hljs-built_in">a_socket</span>_send_lowat<br>lu<span class="hljs-built_in">a_socket</span>_read_timeout<br>lu<span class="hljs-built_in">a_socket</span>_buffer_size<br>lu<span class="hljs-built_in">a_socket</span>_pool_size<br>lu<span class="hljs-built_in">a_socket</span>_keepalive_timeout<br>lu<span class="hljs-built_in">a_socket</span>_log_errors<br>lu<span class="hljs-built_in">a_ssl</span>_ciphers<br>lu<span class="hljs-built_in">a_ssl</span>_crl<br>lu<span class="hljs-built_in">a_ssl</span>_protocols<br>lu<span class="hljs-built_in">a_ssl</span>_trusted_certificate<br>lu<span class="hljs-built_in">a_ssl</span>_verify_depth<br>lu<span class="hljs-built_in">a_http10</span>_buffering<br>rewrite_by_lu<span class="hljs-built_in">a_no</span>_postpone<br>lu<span class="hljs-built_in">a_transform</span>_underscores_in_response_headers<br>lu<span class="hljs-built_in">a_check</span>_client_abort<br>lu<span class="hljs-built_in">a_max</span>_pending_timers<br>lu<span class="hljs-built_in">a_max</span>_running_timers<br></code></pre></td></tr></table></figure>
<p>这些指令都是 nginx 访问 lua 脚本的入口。</p>
<h2 id="lua-访问nginx-API"><a href="#lua-访问nginx-API" class="headerlink" title="lua 访问nginx API"></a>lua 访问nginx API</h2><p>lua脚本如何调用nginx中的函数呢？就是通过 ngx_lua 的API 。</p>
<p>具体介绍参见：<a target="_blank" rel="noopener" href="https://www.nginx.com/resources/wiki/modules/lua/#nginx-api-for-lua">https://www.nginx.com/resources/wiki/modules/lua/#nginx-api-for-lua</a></p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br></pre></td><td class="code"><pre><code class="hljs stylus">Introduction<br>ngx<span class="hljs-selector-class">.arg</span><br>ngx<span class="hljs-selector-class">.var</span><span class="hljs-selector-class">.VARIABLE</span><br>Core constants<br>HTTP method constants<br>HTTP status constants<br>NGINX log level constants<br>print<br>ngx<span class="hljs-selector-class">.ctx</span><br>ngx<span class="hljs-selector-class">.location</span><span class="hljs-selector-class">.capture</span><br>ngx<span class="hljs-selector-class">.location</span><span class="hljs-selector-class">.capture_multi</span><br>ngx<span class="hljs-selector-class">.status</span><br>ngx<span class="hljs-selector-class">.header</span><span class="hljs-selector-class">.HEADER</span><br>ngx<span class="hljs-selector-class">.resp</span><span class="hljs-selector-class">.get_headers</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.start_time</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.http_version</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.raw_header</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_method</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_method</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_uri</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_uri_args</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_uri_args</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_post_args</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_headers</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_header</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.clear_header</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.read_body</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.discard_body</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_body_data</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.get_body_file</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_body_data</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.set_body_file</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.init_body</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.append_body</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.finish_body</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.socket</span><br>ngx<span class="hljs-selector-class">.req</span><span class="hljs-selector-class">.is_internal</span><br>ngx<span class="hljs-selector-class">.exec</span><br>ngx<span class="hljs-selector-class">.redirect</span><br>ngx<span class="hljs-selector-class">.send_headers</span><br>ngx<span class="hljs-selector-class">.headers_sent</span><br>ngx<span class="hljs-selector-class">.print</span><br>ngx<span class="hljs-selector-class">.say</span><br>ngx<span class="hljs-selector-class">.log</span><br>ngx<span class="hljs-selector-class">.flush</span><br>ngx<span class="hljs-selector-class">.exit</span><br>ngx<span class="hljs-selector-class">.eof</span><br>ngx<span class="hljs-selector-class">.sleep</span><br>ngx<span class="hljs-selector-class">.escape_uri</span><br>ngx<span class="hljs-selector-class">.unescape_uri</span><br>ngx<span class="hljs-selector-class">.encode_args</span><br>ngx<span class="hljs-selector-class">.decode_args</span><br>ngx<span class="hljs-selector-class">.encode_base64</span><br>ngx<span class="hljs-selector-class">.decode_base64</span><br>ngx<span class="hljs-selector-class">.crc32_short</span><br>ngx<span class="hljs-selector-class">.crc32_long</span><br>ngx<span class="hljs-selector-class">.hmac_sha1</span><br>ngx<span class="hljs-selector-class">.md5</span><br>ngx<span class="hljs-selector-class">.md5_bin</span><br>ngx<span class="hljs-selector-class">.sha1_bin</span><br>ngx<span class="hljs-selector-class">.quote_sql_str</span><br>ngx<span class="hljs-selector-class">.today</span><br>ngx<span class="hljs-selector-class">.time</span><br>ngx<span class="hljs-selector-class">.now</span><br>ngx<span class="hljs-selector-class">.update_time</span><br>ngx<span class="hljs-selector-class">.localtime</span><br>ngx<span class="hljs-selector-class">.utctime</span><br>ngx<span class="hljs-selector-class">.cookie_time</span><br>ngx<span class="hljs-selector-class">.http_time</span><br>ngx<span class="hljs-selector-class">.parse_http_time</span><br>ngx<span class="hljs-selector-class">.is_subrequest</span><br>ngx<span class="hljs-selector-class">.re</span><span class="hljs-selector-class">.match</span><br>ngx<span class="hljs-selector-class">.re</span><span class="hljs-selector-class">.find</span><br>ngx<span class="hljs-selector-class">.re</span><span class="hljs-selector-class">.gmatch</span><br>ngx<span class="hljs-selector-class">.re</span><span class="hljs-selector-class">.sub</span><br>ngx<span class="hljs-selector-class">.re</span><span class="hljs-selector-class">.gsub</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.get</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.get_stale</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.set</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.safe_set</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.add</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.safe_add</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.replace</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.delete</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.incr</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.flush_all</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.flush_expired</span><br>ngx<span class="hljs-selector-class">.shared</span><span class="hljs-selector-class">.DICT</span><span class="hljs-selector-class">.get_keys</span><br>ngx<span class="hljs-selector-class">.socket</span><span class="hljs-selector-class">.udp</span><br>udpsock:setpeername<br>udpsock:send<br>udpsock:receive<br>udpsock:close<br>udpsock:settimeout<br>ngx<span class="hljs-selector-class">.socket</span><span class="hljs-selector-class">.tcp</span><br>tcpsock:connect<br>tcpsock:sslhandshake<br>tcpsock:send<br>tcpsock:receive<br>tcpsock:receiveuntil<br>tcpsock:close<br>tcpsock:settimeout<br>tcpsock:setoption<br>tcpsock:setkeepalive<br>tcpsock:getreusedtimes<br>ngx<span class="hljs-selector-class">.socket</span><span class="hljs-selector-class">.connect</span><br>ngx<span class="hljs-selector-class">.get_phase</span><br>ngx<span class="hljs-selector-class">.thread</span><span class="hljs-selector-class">.spawn</span><br>ngx<span class="hljs-selector-class">.thread</span><span class="hljs-selector-class">.wait</span><br>ngx<span class="hljs-selector-class">.thread</span><span class="hljs-selector-class">.kill</span><br>ngx<span class="hljs-selector-class">.on_abort</span><br>ngx<span class="hljs-selector-class">.timer</span><span class="hljs-selector-class">.at</span><br>ngx<span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.debug</span><br>ngx<span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.prefix</span><br>ngx<span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.nginx_version</span><br>ngx<span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.nginx_configure</span><br>ngx<span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.ngx_lua_version</span><br>ngx<span class="hljs-selector-class">.worker</span><span class="hljs-selector-class">.exiting</span><br>ngx<span class="hljs-selector-class">.worker</span><span class="hljs-selector-class">.pid</span><br>ndk<span class="hljs-selector-class">.set_var</span><span class="hljs-selector-class">.DIRECTIVE</span><br>coroutine<span class="hljs-selector-class">.create</span><br>coroutine<span class="hljs-selector-class">.resume</span><br>coroutine<span class="hljs-selector-class">.yield</span><br>coroutine<span class="hljs-selector-class">.wrap</span><br>coroutine<span class="hljs-selector-class">.running</span><br>coroutine.status<br></code></pre></td></tr></table></figure>

<p>其实nginx和Lua的交互开发主要就是指令和API，当然还有lua脚本的语法。<code>指令</code>是nginx访问lua的入口，<code>API</code>是lua调用nginx的函数，lua是脚本编程语言。</p>
<p><code>指令</code>其实很简单，所以主要就是熟悉ngx_lua的 API 和Lua语法。</p>
<h1 id="lua-访问-redis"><a href="#lua-访问-redis" class="headerlink" title="lua 访问 redis"></a>lua 访问 redis</h1><p>lua-resty-redis 模块：<a target="_blank" rel="noopener" href="https://github.com/openresty/lua-resty-redis">https://github.com/openresty/lua-resty-redis</a> （有文档可以参考）</p>
<p>在nginx.conf中加入：</p>
<figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs crmsh"><span class="hljs-keyword">location</span> <span class="hljs-title">/redis_test</span>&#123;<br>    content_by_lua_file lua/redis_test.lua;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>redis_test.lua 内容:</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs applescript">[root@localhost lua]<span class="hljs-comment"># cat redis_test.lua</span><br><span class="hljs-keyword">local</span> redis = require <span class="hljs-string">&quot;resty.redis&quot;</span><br><span class="hljs-keyword">local</span> red = redis:new()<br><br>red:set_timeout(<span class="hljs-number">1000</span>)<br><br><span class="hljs-keyword">local</span> ok, err = red:connect(<span class="hljs-string">&quot;127.0.0.1&quot;</span>, <span class="hljs-number">6379</span>)<br><span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>        ngx.<span class="hljs-built_in">say</span>(<span class="hljs-string">&quot;failed to connect: &quot;</span>, err)<br><span class="hljs-built_in">        return</span><br><span class="hljs-keyword">end</span><br><br>ngx.<span class="hljs-built_in">say</span>(<span class="hljs-string">&quot;set result: &quot;</span>, ok)<br><br><span class="hljs-keyword">local</span> res, err = red:<span class="hljs-keyword">get</span>(<span class="hljs-string">&quot;dog&quot;</span>)<br><span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> res <span class="hljs-keyword">then</span><br>        ngx.<span class="hljs-built_in">say</span>(<span class="hljs-string">&quot;failed to get doy: &quot;</span>, err)<br><span class="hljs-built_in">        return</span><br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">if</span> res == ngx.null <span class="hljs-keyword">then</span><br>        ngx.<span class="hljs-built_in">say</span>(<span class="hljs-string">&quot;dog not found.&quot;</span>)<br><span class="hljs-built_in">        return</span><br><span class="hljs-keyword">end</span><br><br>ngx.<span class="hljs-built_in">say</span>(<span class="hljs-string">&quot;dog: &quot;</span>, res)<br><br>[root@localhost lua]<span class="hljs-comment">#</span><br></code></pre></td></tr></table></figure>

<p>访问：</p>
<figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs vim">[root@localhost <span class="hljs-keyword">lua</span>]# curl localhost/redis_test<br><span class="hljs-keyword">set</span> resul<span class="hljs-variable">t:</span> <span class="hljs-number">1</span><br><span class="hljs-keyword">do</span><span class="hljs-variable">g:</span> <span class="hljs-keyword">an</span> animal<br>[root@localhost <span class="hljs-keyword">lua</span>]#<br></code></pre></td></tr></table></figure>
<p>我们看到访问成功。</p>
<h1 id="lua-访问mysql"><a href="#lua-访问mysql" class="headerlink" title="lua 访问mysql"></a>lua 访问mysql</h1><p>openresty的mysql模块：lua-resty-mysql :<a target="_blank" rel="noopener" href="https://github.com/openresty/lua-resty-mysql%EF%BC%88%E6%9C%89%E6%96%87%E6%A1%A3%E5%8F%AF%E4%BB%A5%E5%8F%82%E8%80%83%EF%BC%89">https://github.com/openresty/lua-resty-mysql（有文档可以参考）</a></p>
<p>在nginx.conf加入如下配置：</p>
<figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs crmsh"><span class="hljs-keyword">location</span> <span class="hljs-title">/mysql_test</span> &#123;<br>    content_by_lua_file lua/mysql_test.lua;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>mysql_test.lua脚本内容：</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><code class="hljs stata">[root@localhost lua]# <span class="hljs-keyword">pwd</span><br>/opt/openresty/nginx/lua<br>[root@localhost lua]# <span class="hljs-keyword">cat</span> mysql_test.lua<br><span class="hljs-keyword">local</span> mysql = require <span class="hljs-string">&quot;resty.mysql&quot;</span><br><span class="hljs-keyword">local</span> <span class="hljs-keyword">db</span>, <span class="hljs-keyword">err</span> = mysql:new()<br><br><span class="hljs-keyword">if</span> not <span class="hljs-keyword">db</span> then<br>        ngx.say(<span class="hljs-string">&quot;failed to instantiate mysql: &quot;</span>, <span class="hljs-keyword">err</span>)<br>        <span class="hljs-keyword">return</span><br>end<br><br><span class="hljs-keyword">db</span>:set_timeout(1000)<br><br><span class="hljs-keyword">local</span> ok, <span class="hljs-keyword">err</span>, errno, sqlstate = <span class="hljs-keyword">db</span>:connect&#123;<br>        host = <span class="hljs-string">&quot;127.0.0.1&quot;</span>,<br>        port = 3306,<br>        database = <span class="hljs-string">&quot;ngx_lua&quot;</span>,<br>        user = <span class="hljs-string">&quot;root&quot;</span>,<br>        password=<span class="hljs-string">&quot;digdeep&quot;</span>,<br>        max_packet_size = 1024 * 1024<br>&#125;<br><br><span class="hljs-keyword">if</span> not ok then<br>        ngx.say(<span class="hljs-string">&quot;failed to connect: &quot;</span>, <span class="hljs-keyword">err</span>, <span class="hljs-string">&quot;: &quot;</span>, errno, <span class="hljs-string">&quot; &quot;</span>, sqlstate)<br>        <span class="hljs-keyword">return</span><br>end<br><br>ngx.say(<span class="hljs-string">&quot;connected to mysql.&quot;</span>)<br><br><span class="hljs-keyword">local</span> res, <span class="hljs-keyword">err</span>, errno, sqlstate = <span class="hljs-keyword">db</span>:<span class="hljs-keyword">query</span>(<span class="hljs-string">&quot;drop table if exists cats&quot;</span>)<br><span class="hljs-keyword">if</span> not res then<br>        ngx.say(<span class="hljs-string">&quot;bad result: &quot;</span>, <span class="hljs-keyword">err</span>, <span class="hljs-string">&quot;: &quot;</span>, errno, <span class="hljs-string">&quot;: &quot;</span>, sqlstate, <span class="hljs-string">&quot;.&quot;</span>)<br>        <span class="hljs-keyword">return</span><br>end<br><br>res, <span class="hljs-keyword">err</span>, errno, sqlstate = <span class="hljs-keyword">db</span>:<span class="hljs-keyword">query</span>(<span class="hljs-string">&quot;create table cats &quot;</span> .. <span class="hljs-string">&quot;(id int not null primary key auto_increment, &quot;</span><br>                                        .. <span class="hljs-string">&quot;name varchar(30))&quot;</span>)<br><span class="hljs-keyword">if</span> not res then<br>        ngx.say(<span class="hljs-string">&quot;bad result: &quot;</span>, <span class="hljs-keyword">err</span>, <span class="hljs-string">&quot;: &quot;</span>, errno, <span class="hljs-string">&quot;: &quot;</span>, sqlstate, <span class="hljs-string">&quot;.&quot;</span>)<br>        <span class="hljs-keyword">return</span><br>end<br><br>ngx.say(<span class="hljs-string">&quot;table cats created.&quot;</span>)<br><br>res, <span class="hljs-keyword">err</span>, errno, sqlstate = <span class="hljs-keyword">db</span>:<span class="hljs-keyword">query</span>(<span class="hljs-string">&quot;insert into cats(name) &quot;</span> .. <span class="hljs-string">&quot;values (\&#x27;Bob\&#x27;),(\&#x27;\&#x27;),(null)&quot;</span>)<br><span class="hljs-keyword">if</span> not res then<br>        ngx.say(<span class="hljs-string">&quot;bad request: &quot;</span>, <span class="hljs-keyword">err</span>, <span class="hljs-string">&quot;: &quot;</span>, errno, <span class="hljs-string">&quot;: &quot;</span>, sqlstate, <span class="hljs-string">&quot;.&quot;</span>)<br>        <span class="hljs-keyword">return</span><br>end<br><br>ngx.say(res.affected_rows, <span class="hljs-string">&quot; rows inserted into table cats &quot;</span>, <span class="hljs-string">&quot;(last insert id: &quot;</span>, res.insert_id, <span class="hljs-string">&quot;)&quot;</span>)<br><br>res, <span class="hljs-keyword">err</span>, errno, sqlstate = <span class="hljs-keyword">db</span>:<span class="hljs-keyword">query</span>(<span class="hljs-string">&quot;select * from cats order by id asc&quot;</span>, 10)<br><span class="hljs-keyword">if</span> not res then<br>        ngx.say(<span class="hljs-string">&quot;bad result &quot;</span>, <span class="hljs-keyword">err</span>, <span class="hljs-string">&quot;: &quot;</span>, errno, <span class="hljs-string">&quot;: &quot;</span>, sqlstate, <span class="hljs-string">&quot;.&quot;</span>)<br>        <span class="hljs-keyword">return</span><br>end<br><br><span class="hljs-keyword">local</span> cjson = require <span class="hljs-string">&quot;cjson&quot;</span><br>ngx.say(<span class="hljs-string">&quot;result: &quot;</span>, cjson.<span class="hljs-keyword">encode</span>(res))<br><br><span class="hljs-keyword">local</span> ok, <span class="hljs-keyword">err</span> = <span class="hljs-keyword">db</span>:set_keepalive(1000, 100)<br><span class="hljs-keyword">if</span> not ok then<br>        ngx.say(<span class="hljs-string">&quot;failed to set keepalive: &quot;</span>, <span class="hljs-keyword">err</span>)<br>        <span class="hljs-keyword">return</span><br>end<br></code></pre></td></tr></table></figure>
<p>测试：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs pgsql">[root@localhost lua]# curl localhost/mysql_test<br>connected <span class="hljs-keyword">to</span> mysql.<br><span class="hljs-keyword">table</span> cats created.<br><span class="hljs-number">3</span> <span class="hljs-keyword">rows</span> inserted <span class="hljs-keyword">into</span> <span class="hljs-keyword">table</span> cats (last <span class="hljs-keyword">insert</span> id: <span class="hljs-number">1</span>)<br>result: [&#123;&quot;name&quot;:&quot;Bob&quot;,&quot;id&quot;:<span class="hljs-number">1</span>&#125;,&#123;&quot;name&quot;:&quot;&quot;,&quot;id&quot;:<span class="hljs-number">2</span>&#125;,&#123;&quot;name&quot;:<span class="hljs-keyword">null</span>,&quot;id&quot;:<span class="hljs-number">3</span>&#125;]<br><br></code></pre></td></tr></table></figure>
<p>测试通过。</p>
<h1 id="lua-的-capture-和-capture-multi-子查询"><a href="#lua-的-capture-和-capture-multi-子查询" class="headerlink" title="lua 的 capture 和 capture_multi(子查询)"></a>lua 的 capture 和 capture_multi(子查询)</h1><p>capture_multi 是 openresty 一个十分强大的功能。它能极大的减少前端浏览器发送的http请求的数量，突破了浏览器对于同一个服务器并发请求数量的限制，因为他可以将前端的多个http请求减少为只要一个http请求到nginx，然后nginx使用capture_multi特性，对后端发起多个异步并发请求，然后统一将结果返回给前端。下面看一个例子：</p>
<p>首先在nginx.conf中加入下面的 location 配置，并且配置好 nginx 访问 php 的配置：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-attribute">location</span> /capture &#123;<br>    <span class="hljs-attribute">content_by_lua_file</span> lua/capture.lua;<br>    <span class="hljs-comment">#access_by_lua_file lua/capture.lua;</span><br>&#125;<br><br><span class="hljs-attribute">location</span> <span class="hljs-regexp">~ \.php$</span> &#123;<br>    <span class="hljs-attribute">root</span>           html;<br>    <span class="hljs-attribute">fastcgi_pass</span>   <span class="hljs-number">127.0.0.1:9000</span>;<br>    <span class="hljs-attribute">fastcgi_index</span>  index.php;<br>    <span class="hljs-attribute">fastcgi_param</span>  SCRIPT_FILENAME  $document_root$fastcgi_script_name;<br>    <span class="hljs-attribute">include</span>        fastcgi_params;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>capture.lua 的代码如下：</p>
<figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs vim">[root@localhost <span class="hljs-keyword">lua</span>]# <span class="hljs-keyword">pwd</span><br>/<span class="hljs-keyword">opt</span>/openresty/nginx/<span class="hljs-keyword">lua</span><br>[root@localhost <span class="hljs-keyword">lua</span>]# <span class="hljs-keyword">cat</span> capture.<span class="hljs-keyword">lua</span><br>local res1,res2,res3,res4 = ngx.location.capture_multi&#123;<br>        &#123;<span class="hljs-string">&quot;/mysql_test&quot;</span>, &#123;<span class="hljs-keyword">args</span>=<span class="hljs-string">&quot;t=1&amp;id=1&quot;</span>&#125;&#125;,<br>        &#123;<span class="hljs-string">&quot;/redis_test&quot;</span>, &#123;<span class="hljs-keyword">args</span>=<span class="hljs-string">&quot;t=2&amp;id=2&quot;</span>&#125;&#125;,<br>        &#123;<span class="hljs-string">&quot;/lua&quot;</span>, &#123;<span class="hljs-keyword">args</span>=<span class="hljs-string">&quot;t=3&amp;id=3&quot;</span>&#125;&#125;,<br>        &#123;<span class="hljs-string">&quot;/index.php&quot;</span>, &#123;<span class="hljs-keyword">args</span>=<span class="hljs-string">&quot;t=3&amp;id=3&quot;</span>&#125;&#125;,<br>&#125;<br><br>ngx.header.content_type=<span class="hljs-string">&quot;text/plain&quot;</span><br>ngx.say(res1.body)<br>ngx.say(res2.body)<br>ngx.say(res3.body)<br>ngx.say(res4.truncated)<br>ngx.say(res4.status)<br>ngx.say(res4.header[<span class="hljs-string">&quot;Set-Cookie&quot;</span>])<br><br>--ngx.say(res4.body)<br></code></pre></td></tr></table></figure>
<p>index.php 代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs php">[root@localhost html]<span class="hljs-comment"># pwd</span><br>/opt/openresty/nginx/html<br>[root@localhost html]<span class="hljs-comment"># cat index.php</span><br><span class="hljs-meta">&lt;?php</span><br>        <span class="hljs-keyword">echo</span> phpinfo();<br><span class="hljs-meta">?&gt;</span><br></code></pre></td></tr></table></figure>


<p>访问：</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs applescript">[root@localhost html]<span class="hljs-comment"># curl localhost/capture</span><br>connected <span class="hljs-keyword">to</span> mysql.<br>table cats created.<br><span class="hljs-number">3</span> rows inserted <span class="hljs-keyword">into</span> table cats (<span class="hljs-keyword">last</span> insert <span class="hljs-built_in">id</span>: <span class="hljs-number">1</span>)<br><span class="hljs-literal">result</span>: [&#123;<span class="hljs-string">&quot;name&quot;</span>:<span class="hljs-string">&quot;Bob&quot;</span>,<span class="hljs-string">&quot;id&quot;</span>:<span class="hljs-number">1</span>&#125;,&#123;<span class="hljs-string">&quot;name&quot;</span>:<span class="hljs-string">&quot;&quot;</span>,<span class="hljs-string">&quot;id&quot;</span>:<span class="hljs-number">2</span>&#125;,&#123;<span class="hljs-string">&quot;name&quot;</span>:null,<span class="hljs-string">&quot;id&quot;</span>:<span class="hljs-number">3</span>&#125;]<br><br><span class="hljs-keyword">set</span> <span class="hljs-literal">result</span>: <span class="hljs-number">1</span><br>dog: an animal<br><br>hello ngx_lua!!!!<br><br><span class="hljs-literal">false</span><br><span class="hljs-number">200</span><br>nil<br></code></pre></td></tr></table></figure>
<p>可以看到访问成功了。/mysql_test，/redis_test, /lua, /index.php 四个请求的结果都输出了。</p>
<blockquote>
<p>注意： ngx.location.capture_multi{… …} 中的多个异步并发请求可以是 nginx.conf 中配置的 location(比如 /mysql_test, /redis_test, /lua)，也可以不是 location配置的路径，比如 index.php 就不是。index.php 就是一个简单的后台php 脚本。当然也可以是一个 java 实现的后台接口。</p>
</blockquote>
<h1 id="openresty的缓存-lua-shared-dict"><a href="#openresty的缓存-lua-shared-dict" class="headerlink" title="openresty的缓存 lua_shared_dict"></a>openresty的缓存 lua_shared_dict</h1><p>定义一个缓存：</p>
<p>在nginx的配置文件 nginx.conf 的 http 端下面加入指令：</p>
<figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs abnf">lua_shared_dict ngx_cache <span class="hljs-number">128</span>m<span class="hljs-comment">;</span><br></code></pre></td></tr></table></figure>


<p>就定义了一个 名称为 ngx_cache 大小为128m的内存用于缓存，注意该缓存是所有nginx work process所共享的。</p>
<p>在lua脚本中访问缓存：</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs maxima"><span class="hljs-built_in">local</span> ngx_cache = ngx.shared.ngx_cache<br><span class="hljs-built_in">local</span> value = ngx_cache:<span class="hljs-built_in">get</span>(<span class="hljs-built_in">key</span>)<br><br><span class="hljs-built_in">local</span> succ, err, forcible = ngx_cache:set(<span class="hljs-built_in">key</span>, value, exptime)<br></code></pre></td></tr></table></figure>


<p>下面测试一下，首先在 nginx.conf的server端中加入：</p>
<div class="code-wrapper"><pre><code class="hljs">location /cache &#123;
    content_by_lua_file lua/cache.lua;
&#125;
</code></pre></div>
<p>然后编写 cache.lua 脚本：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><code class="hljs pgsql">[root@localhost lua]# cat cache.lua<br><span class="hljs-keyword">local</span> redis = require &quot;resty.redis&quot;<br><span class="hljs-keyword">local</span> red = redis:<span class="hljs-built_in">new</span>()<br><br><span class="hljs-keyword">function</span> set_to_cache(key, <span class="hljs-keyword">value</span>, exptime)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> exptime <span class="hljs-keyword">then</span><br>                exptime = <span class="hljs-number">0</span><br>        <span class="hljs-keyword">end</span><br>        <span class="hljs-keyword">local</span> ngx_cache = ngx.shared.ngx_cache<br>        <span class="hljs-keyword">local</span> succ, err, forcible = ngx_cache:<span class="hljs-keyword">set</span>(key, <span class="hljs-keyword">value</span>, exptime)<br>        <span class="hljs-keyword">return</span> succ<br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> get_from_cache(key)<br>        <span class="hljs-keyword">local</span> ngx_cache = ngx.shared.ngx_cache;<br>        <span class="hljs-keyword">local</span> <span class="hljs-keyword">value</span> = ngx_cache:<span class="hljs-keyword">get</span>(key)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">then</span><br>                <span class="hljs-keyword">value</span> = get_from_redis(key)<br>                set_to_cache(key, <span class="hljs-keyword">value</span>)<br>                <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span><br>        <span class="hljs-keyword">end</span><br><br>        ngx.say(&quot;get from cache.&quot;)<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span><br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> get_from_redis(key)<br>        red:set_timeout(<span class="hljs-number">1000</span>)<br><br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">connect</span>(&quot;127.0.0.1&quot;, <span class="hljs-number">6379</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to connect: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br><br>        <span class="hljs-keyword">local</span> res, err = red:<span class="hljs-keyword">get</span>(key)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> res <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to get doy: &quot;, err)<br>                <span class="hljs-keyword">return</span> ngx.<span class="hljs-keyword">null</span><br>        <span class="hljs-keyword">end</span><br><br>        ngx.say(&quot;get from redis.&quot;)<br>        <span class="hljs-keyword">return</span> res<br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> set_to_redis(key, <span class="hljs-keyword">value</span>)<br>        red:set_timeout(<span class="hljs-number">1000</span>)<br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">connect</span>(&quot;127.0.0.1&quot;, <span class="hljs-number">6379</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to connect: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br><br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">set</span>(key, <span class="hljs-keyword">value</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to set to redis: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br>        <span class="hljs-keyword">return</span> ok<br><span class="hljs-keyword">end</span><br><br>set_to_redis(<span class="hljs-string">&#x27;dog&#x27;</span>, &quot;Bob&quot;)<br><span class="hljs-keyword">local</span> rs = get_from_cache(<span class="hljs-string">&#x27;dog&#x27;</span>)<br>ngx.say(rs)<br></code></pre></td></tr></table></figure>
<p>测试：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs csharp">[<span class="hljs-meta">root@localhost ~</span>]<span class="hljs-meta"># curl localhost/cache</span><br><span class="hljs-keyword">get</span> <span class="hljs-keyword">from</span> redis.<br>Bob<br>[<span class="hljs-meta">root@localhost ~</span>]<span class="hljs-meta"># curl localhost/cache</span><br><span class="hljs-keyword">get</span> <span class="hljs-keyword">from</span> cache.<br>Bob<br>[<span class="hljs-meta">root@localhost ~</span>]<span class="hljs-meta"># curl localhost/cache</span><br><span class="hljs-keyword">get</span> <span class="hljs-keyword">from</span> cache.<br>Bob<br></code></pre></td></tr></table></figure>
<p>第一次从 redis中获取，以后每次都从cache中获取。</p>
<p>可以使用 ab 测试一下rps(Requests per second):</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-attribute">ab</span> -n <span class="hljs-number">1000</span> -c <span class="hljs-number">100</span> -k http://<span class="hljs-number">127.0.0.1</span>/cache<br></code></pre></td></tr></table></figure>

<h1 id="解决缓存失效风暴-lua-resty-lock"><a href="#解决缓存失效风暴-lua-resty-lock" class="headerlink" title="解决缓存失效风暴 lua-resty-lock"></a>解决缓存失效风暴 lua-resty-lock</h1><p>缓存失效风暴是指缓存因为时间过期而失效时，会导致所有的请求都去访问 后台的redis或者mysql，而导致CPU性能即刻增长的现象。所以关键是当缓存失效时，用lock保证只有一个线程去访问后台的redis或者mysql，然后更新缓存。需要使用到 lua-resty-lock 模块的加锁、解锁功能。</p>
<p>lua-resty-lock 文档：<a target="_blank" rel="noopener" href="https://github.com/openresty/lua-resty-lock">https://github.com/openresty/lua-resty-lock</a></p>
<p>首先在nginx.conf 的 http 端下面加入指令：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-attribute">lua_shared_dict</span> ngx_cache <span class="hljs-number">128m</span>;     <span class="hljs-comment"># cache</span><br><span class="hljs-attribute">lua_shared_dict</span> cache_lock <span class="hljs-number">100k</span>;    <span class="hljs-comment"># lock for cache</span><br></code></pre></td></tr></table></figure>
<p>然后在nginx.conf的server端中加入：</p>
<figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs crmsh"><span class="hljs-keyword">location</span> <span class="hljs-title">/cache_lock</span> &#123;<br>    content_by_lua_file lua/cache_lock.lua;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>cache_lock.lua代码：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><code class="hljs pgsql">[root@localhost lua]# cat cache_lock.lua<br><span class="hljs-keyword">local</span> redis = require &quot;resty.redis&quot;<br><span class="hljs-keyword">local</span> red = redis:<span class="hljs-built_in">new</span>()<br><span class="hljs-keyword">local</span> resty_lock = require &quot;resty.lock&quot;<br><span class="hljs-keyword">local</span> ngx_cache = ngx.shared.ngx_cache<br><br><span class="hljs-keyword">function</span> set_to_cache(key, <span class="hljs-keyword">value</span>, exptime)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> exptime <span class="hljs-keyword">then</span><br>                exptime = <span class="hljs-number">0</span><br>        <span class="hljs-keyword">end</span><br>        <span class="hljs-keyword">local</span> succ, err, forcible = ngx_cache:<span class="hljs-keyword">set</span>(key, <span class="hljs-keyword">value</span>, exptime)<br>        <span class="hljs-keyword">return</span> succ<br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> get_from_cache(key)<br>        <span class="hljs-keyword">local</span> ngx_cache = ngx.shared.ngx_cache;<br>        <span class="hljs-keyword">local</span> <span class="hljs-keyword">value</span> = ngx_cache:<span class="hljs-keyword">get</span>(key)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">then</span>       <span class="hljs-comment">-- cache miss</span><br>                <span class="hljs-keyword">local</span> <span class="hljs-keyword">lock</span> = resty_lock:<span class="hljs-built_in">new</span>(&quot;cache_lock&quot;)<br>                <span class="hljs-keyword">local</span> elapsed, err = <span class="hljs-keyword">lock</span>:<span class="hljs-keyword">lock</span>(key)<br>                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> elapsed <span class="hljs-keyword">then</span><br>                        <span class="hljs-keyword">return</span> fail(&quot;failed to acquire the lock: &quot;, err)<br>                <span class="hljs-keyword">end</span><br><br>                <span class="hljs-keyword">value</span> = get_from_redis(key)<br>                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">then</span><br>                        <span class="hljs-keyword">local</span> ok, err = <span class="hljs-keyword">lock</span>:unlock()<br>                        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                                <span class="hljs-keyword">return</span> fail(&quot;failed to unlock: &quot;, err)<br>                        <span class="hljs-keyword">end</span><br>                        ngx.say(&quot;no value found&quot;)<br>                        <span class="hljs-keyword">return</span><br>                <span class="hljs-keyword">end</span><br><br>                <span class="hljs-keyword">local</span> ok, err = ngx_cache:<span class="hljs-keyword">set</span>(key, <span class="hljs-keyword">value</span>, <span class="hljs-number">1</span>)<br>                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                        <span class="hljs-keyword">local</span> ok, err = <span class="hljs-keyword">lock</span>:unlock()<br>                        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                                <span class="hljs-keyword">return</span> fail(&quot;failed to unlock: &quot;, err)<br>                        <span class="hljs-keyword">end</span><br>                        <span class="hljs-keyword">return</span> faile(&quot;failed to update ngx_cache: &quot;, err)<br>                <span class="hljs-keyword">end</span><br><br>                <span class="hljs-keyword">local</span> ok, err = <span class="hljs-keyword">lock</span>:unlock()<br>                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                        <span class="hljs-keyword">return</span> faile(&quot;failed to unlock: &quot;, err)<br>                <span class="hljs-keyword">end</span><br><br>                <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span><br>        <span class="hljs-keyword">end</span><br><br>        ngx.say(&quot;get from cache.&quot;)<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span><br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> get_from_redis(key)<br>        red:set_timeout(<span class="hljs-number">1000</span>)<br><br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">connect</span>(&quot;127.0.0.1&quot;, <span class="hljs-number">6379</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to connect: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br><br>        <span class="hljs-keyword">local</span> res, err = red:<span class="hljs-keyword">get</span>(key)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> res <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to get doy: &quot;, err)<br>                <span class="hljs-keyword">return</span> ngx.<span class="hljs-keyword">null</span><br>        <span class="hljs-keyword">end</span><br><br>        ngx.say(&quot;get from redis.&quot;)<br>        <span class="hljs-keyword">return</span> res<br><span class="hljs-keyword">end</span><br><br><span class="hljs-keyword">function</span> set_to_redis(key, <span class="hljs-keyword">value</span>)<br>        red:set_timeout(<span class="hljs-number">1000</span>)<br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">connect</span>(&quot;127.0.0.1&quot;, <span class="hljs-number">6379</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to connect: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br><br>        <span class="hljs-keyword">local</span> ok, err = red:<span class="hljs-keyword">set</span>(key, <span class="hljs-keyword">value</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> ok <span class="hljs-keyword">then</span><br>                ngx.say(&quot;failed to set to redis: &quot;, err)<br>                <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">end</span><br>        <span class="hljs-keyword">return</span> ok<br><span class="hljs-keyword">end</span><br><br>set_to_redis(<span class="hljs-string">&#x27;dog&#x27;</span>, &quot;Bob&quot;)<br><span class="hljs-keyword">local</span> rs = get_from_cache(<span class="hljs-string">&#x27;dog&#x27;</span>)<br>ngx.say(rs)<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs csharp">[<span class="hljs-meta">root@localhost lua</span>]<span class="hljs-meta"># curl localhost/cache_lock</span><br><span class="hljs-keyword">get</span> <span class="hljs-keyword">from</span> cache.<br>Bob<br>[<span class="hljs-meta">root@localhost lua</span>]<span class="hljs-meta"># curl localhost/cache_lock</span><br><span class="hljs-keyword">get</span> <span class="hljs-keyword">from</span> cache.<br>Bob<br></code></pre></td></tr></table></figure>

<h1 id="openresty-执行阶段"><a href="#openresty-执行阶段" class="headerlink" title="openresty 执行阶段"></a>openresty 执行阶段</h1><p>nginx的执行阶段分成了很多个阶段,所以第三方模块就可以在某个适当的阶段加入一些处理。openresty进行了简化成了7个阶段：</p>
<p>7个阶段的执行顺序如下：</p>
<figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ceylon">set<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: 流程分支判断，判断变量初始哈<br><br>rewrite<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: 用lua脚本实现nginx rewrite<br><br>access<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: ip准入，是否能合法性访问，防火墙<br><br>content<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: 内存生成<br><br>header<span class="hljs-number">_f</span>ilter<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua：过滤http头信息，增加头信息<br><br>body<span class="hljs-number">_f</span>ilter<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: 内容大小写，内容加密<br><br>log<span class="hljs-number">_</span><span class="hljs-meta">by</span><span class="hljs-number">_</span>lua: 本地/远程记录日志<br></code></pre></td></tr></table></figure>
<p>但是其实我们可以只用 content_by_lua，所有功能都在该阶段完成，也是可以的。</p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/digdeep/p/4859575.html">https://www.cnblogs.com/digdeep/p/4859575.html</a></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/">软件开发</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/nginx/">nginx</a>
                    
                      <a class="hover-with-bg" href="/tags/lua/">lua</a>
                    
                      <a class="hover-with-bg" href="/tags/openresty/">openresty</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/04/22/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/01c_cpp/13stl%E4%B8%A5%E6%A0%BC%E5%BC%B1%E5%BA%8Fstric_weak_ordering/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">stl严格弱序(stick weak ordering)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/04/01/04DevOps/16systemd%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E5%8F%8A%E7%AE%A1%E7%90%86%E6%96%B9%E6%B3%95/">
                        <span class="hidden-mobile">systemd配置文件及管理方法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
